"""
========================================================================================================================
@project : my-sanic
@file: demo
@Author: mengying
@email: 652044581@qq.com
@date: 2023/3/14 9:40
@desc: 异步定时器任务全局和局部调用
========================================================================================================================
"""
import time, uuid
from sanic import Sanic
from sanic.response import json
from task.myScheduler import  MyAsyncScheduler
from apscheduler.schedulers.asyncio import AsyncIOScheduler


app = Sanic("task_demo")


def cron_job():
    print('定时任务：打印当前时间:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))



@app.route('/')
async def index(request):

    print("局部的scheduler示例")
    scheduler = AsyncIOScheduler()

    # 每隔10分钟执行一次

    scheduler.add_job(cron_job, 'interval', seconds=2, id=uuid.uuid4().hex)

    # 在每天7点，每隔 5分钟 运行一次 job 方法
    scheduler.add_job(cron_job, 'cron', hour=7, id=uuid.uuid4().hex, minute='*/5')

    # 每天18点05分定时执行
    scheduler.add_job(cron_job, 'cron', hour=18, id=uuid.uuid4().hex, minute='05')


    print(scheduler.get_jobs().__len__())

    scheduler.start()

    return json({"hello": "thank you2"})


@app.route('/simple')
async def index(request):
    print("全局scheduler示例，方便整体定时器的全局管控")
    scheduler = MyAsyncScheduler().get_scheduler()

    # 每隔10分钟执行一次
    if not scheduler.running:
        scheduler.add_job(cron_job, 'interval', seconds=2, id=uuid.uuid4().hex, replace_existing=True)

        # 在每天7点，每隔 5分钟 运行一次 job 方法
        scheduler.add_job(cron_job, 'cron', hour=7, id=uuid.uuid4().hex, minute='*/5')

        # 每天18点05分定时执行
        scheduler.add_job(cron_job, 'cron', hour=18, id=uuid.uuid4().hex, minute='05')

        print(scheduler.get_jobs().__len__())


        scheduler.start()
    print(scheduler.running)
    return json({"hello": "thank you"})


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8999)